package com.example.wangning.mycarofcountry.base;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;

import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.main.MainActivity;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by dllo on 16/1/21.
 */
public class BaseBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //如果接收到的消息是自定义消息
        if (intent.getAction().equals(
                JPushInterface.ACTION_MESSAGE_RECEIVED)) {
            //获取额外数据
            Bundle bundle = intent.getExtras();
            String data = bundle.getString(
                    JPushInterface.EXTRA_MESSAGE);
            Log.i("lanou", "-自定义消息内容为：---" + data);

            if (data != null)
                showNotification(context, data);
        }

        if (isOrderedBroadcast()) {
            setResultData("MyBroadcastReceiver数据发送");
        }
    }

    /**
     * 收到自定义消息之后 在通知栏上显示该消息的notification
     **/
    private void showNotification(Context context, String data) {
        //获得一个notificationManager对象
        NotificationManagerCompat managerCompat =
                NotificationManagerCompat.from(context);

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context);

        builder.setAutoCancel(true);
        builder.setTicker("来新消息了");
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("车之国");
        builder.setContentText(data);

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(
                context, 100, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);//跳转设置

        managerCompat.notify(2, builder.build());//发送消息
    }

}

